[Django] How to find out whether a model's column is a foreign key?

Posted by codethief on Stack Overflow See other posts from Stack Overflow or by codethief
Published on 2010-04-09T14:01:03Z Indexed on 2010/04/09 14:03 UTC
Read the original article Hit count: 265

Filed under:
|
|

I'm dynamically storing information in the database depending on the request:

// table, id and column are provided by the request
table_obj = getattr(models, table)
record = table_obj.objects.get(pk=id)

setattr(record, column, request.POST['value'])

The problem is that request.POST['value'] sometimes contains a foreign record's primary key (i.e. an integer) whereas Django expects the column's value to be an object of type ForeignModel:

Cannot assign "u'122'": "ModelA.b" must be a "ModelB" instance.

Now, is there an elegant way to dynamically check whether b is a column containing foreign keys and what model these keys are linked to? (So that I can load the foreign record by it's primary key and assign it to ModelA?) Or doesn't Django provide information like this to the programmer so I really have to get my hands dirty and use isinstance() on the foreign-key column?

© Stack Overflow or respective owner

Related posts about python

Related posts about django